<template>
	<up-navbar title="幸运集市" :autoBack="false" :bgColor="bgColor" fixed placeholder titleStyle="color:#fff">
		<template #left>
			<view v-if="state.pageLength===1" class="u-nav-slot" @click="goHome">
				<up-icon name="home" size="20" color="#fff"></up-icon>
			</view>
			<view v-else class="u-nav-slot" @click="goBack">
				<up-icon name="arrow-left" size="20" color="#fff"></up-icon>
			</view>
		</template>
	</up-navbar>
	<view v-if="state.luckyInfo">
		<view class="gift-top u-p-30">
			<view class="u-flex u-flex-between u-p-b-30">
				<view class="u-flex u-flex-middle u-font-25 u-text-white">
					<up-icon name="gift-fill" color="#fff" size="22"></up-icon>
					<text class="u-m-l-5 u-font-bold">市集好礼周周送</text>
					<text class="u-text-opacity">｜</text>
					<text class="u-text-opacity">{{state.luckyInfo.fare_type===1?'官方包邮':'付邮领取'}}</text>
				</view>
				<block v-if="state.luckyInfo.is_start===2">
					<view class="u-btn-dy u-font-24" @click="subscribeMessagePreview">订阅抽奖通知</view>
				</block>
				<!-- <view v-else-if="state.luckyInfo.is_end!=1" class="u-btn-dy u-font-24" @click="subscribeMessage">订阅开奖</view> -->
			</view>
			<view class="gift-cover u-rela">
				<view v-if="state.luckyInfo.is_end===1&&state.luckyInfo.draw_record" class="lucky-rules u-abso u-font-26">已开奖</view>
				<view v-else class="lucky-rules u-abso u-font-26" @click="state.ruleShow=true">抽奖规则</view>
				<image mode="widthFix" :src="state.luckyInfo.cover"></image>
			</view>
			<p class="u-m-t-20 u-m-b-20">{{state.luckyInfo.name}}</p>
			<view class="u-flex u-flex-between u-m-t-10 u-content-color u-font-26">
				<view>奖品价值：{{state.luckyInfo.price}}元</view>
			</view>
			<view class="u-flex u-flex-between u-m-t-10 u-content-color u-font-26">
				<view>领奖方式：{{state.luckyInfo.fare_type===1?'官方包邮':'付邮领取'}}</view>
			</view>
			<view class="u-flex u-flex-between u-m-t-10 u-content-color u-font-26">
				<view>放号总量：{{state.luckyInfo.total}}个</view>
			</view>
			<view class="u-flex u-flex-between u-m-t-10 u-content-color u-font-26">
				<view>开奖时间：{{state.luckyInfo.end}}</view>
			</view>
		</view>
		<up-gap height="10" bgColor="#fafafa"></up-gap>
		<view class="u-flex u-flex-between u-p-30 u-font-27">
			<text class="u-content-color u-m-t-10">活动发起方</text>
			<view class="u-flex u-flex-middle">
				<up-avatar src="https://wx.qlogo.cn/mmhead/Mjzdia7evAzzCUqH2AbqN8XJwySgcV0JIBarHV1gDTfRULXCBFL67kZjkCibGdODEQpG8EtibNJhus/0" size="30"></up-avatar>
				<text class="u-m-l-5 u-error-dark">官方发布</text>
			</view>
		</view>
		<block v-if="state.luckyInfo.is_end===1&&state.luckyInfo.draw_record">
			<up-gap height="10" bgColor="#fafafa"></up-gap>
			<view class="u-flex u-flex-between u-p-30 u-font-27">
				<text class="u-content-color">中奖用户</text>
				<view class="u-flex u-flex-middle u-font-25">
					<up-avatar :src="state.luckyInfo.draw_record.user_avatar" size="30"></up-avatar>
					<text class="u-m-l-10">{{state.luckyInfo.draw_record.user_nickname}}</text>
				</view>
			</view>
		</block>
		<block v-if="state.luckyInfo.is_end===1&&state.luckyInfo.draw">
			<up-gap height="10" bgColor="#fafafa"></up-gap>
			<view class="u-flex u-flex-between u-p-30 u-font-27">
				<text class="u-content-color">开奖号码</text>
				<view class="u-flex u-flex-wrap lucky-nums u-font-25">
					<text>{{state.luckyInfo.draw}}</text>
				</view>
			</view>
		</block>
		<view v-if="state.luckyInfo.draw_record" class="u-flex u-flex-between u-p-30 u-font-27">
			<text class="u-content-color">开奖公式</text>
			<view style="width: 70%;">
				<view class="u-flex u-flex-between">
					<text></text>
					<view class="u-flex u-flex-nowrap lucky-nums u-text-right u-font-25" style="max-width: auto;">
						<text>(N1+N2+N3+...+N{{state.claim||state.luckyInfo.claim}})</text>
						<text>=</text>
						<text>{{state.luckyInfo.draw_record.sum_num}}</text>
					</view>
				</view>
				<p class="u-m-t-10 u-light-color u-font-26 u-text-right">备注：后五位{{state.luckyInfo.draw_record.sum_num.slice(-5)}}即为中奖号码参考值</p>
			</view>
		</view>
		<block v-if="state.user_nums.length>0">
			<up-gap height="10" bgColor="#fafafa"></up-gap>
			<view class="u-flex u-flex-between u-p-30 u-font-27">
				<text class="u-content-color">我的幸运号({{state.user_nums.length}})</text>
				<view class="u-flex u-flex-between" style="width: 70%;">
					<text></text>
					<view class="lucky-nums u-font-25 u-text-right">
						<block v-for="(item,index) in state.user_nums" :key="index">
							<text v-if="state.luckyInfo.is_end===1" :class="{'u-text-light':item.num!=state.luckyInfo.draw}">{{item.num}}</text>
							<text v-else>{{item.num}}</text>
						</block>
					</view>
				</view>
			</view>
		</block>
		<up-gap height="10" bgColor="#fafafa"></up-gap>
		<view class="u-p-30">
			<view class="u-p-t-30 u-p-b-30" v-if="state.luckyInfo.is_start===2">
				<up-button type="error" icon="calendar" text="等待开始" shape="circle"></up-button>
				<!-- <up-button type="error" icon="calendar" text="订阅开始提醒" @click="subscribeMessagePreview" shape="circle"></up-button>
				<p class="u-p-t-10 u-text-center u-font-26 u-light-color">活动开始前通知，抢先选号哦！</p> -->
			</view>
			<block v-else>
				<view v-if="state.luckyInfo.is_end===2" class="u-p-t-40">
					<view class="u-p-l-80 u-p-r-80" v-if="state.isFinish">
						<block v-if="state.isFinish&&state.user_nums.length===0">
							<up-button type="info" text="活动已结束" shape="circle"></up-button>
						</block>
						<!-- <view v-else-if="state.luckyInfo.claim>0">
							<up-button type="error" text="已开奖，查看详情" shape="circle" @click="toDetail(id)"></up-button>
						</view> -->
						<block v-else-if="state.user_nums.length">
							<!-- <up-button type="error" disabled :text="'已选'+state.user_nums.length+'个号，等待开奖'" shape="circle"></up-button> -->
							<up-button type="error" disabled text="正在计算开奖，预计2分钟" shape="circle"></up-button>
						</block>
					</view>
					<block v-else-if="state.luckyInfo.single>state.user_nums.length">
						<view class="u-p-l-80 u-p-r-80 u-flex u-flex-between">
							<view style="width: 68%;">
								<up-button type="error" text="开始选号" shape="circle" @click="chooseNum"></up-button>
							</view>
							<view style="width: 30%;">
								<up-button type="success" text="幸运随机" plain shape="circle" @click="randomNum"></up-button>
							</view>
						</view>
						<p class="u-font-25 u-text-center u-p-t-15 u-light-color">
							<text>消耗{{state.luckyInfo.integral}}幸运星/号，已选{{state.user_nums.length}}/{{state.luckyInfo.single}}</text>
						</p>
					</block>
					<view class="u-p-l-80 u-p-r-80" v-else>
						<up-button type="warning" text="达到选号上限，请等待开奖" shape="circle"></up-button>
					</view>
				</view>
				<block v-else>
					<!-- 已参与，中奖 -->
					<view v-if="state.luckyInfo.draw_user_id===userInfo.id" class="u-p-l-80 u-p-r-80 u-p-t-40">
						<p class="u-font-25 u-text-center u-p-b-20 u-error-dark">星光不负赶路人，幸运偏爱坚持的你！</p>
						<up-button v-if="!state.luckyInfo.cash_address" type="error" text="去领奖" shape="circle" @click="toBuyHistory"></up-button>
						<block v-else>
							<!-- 兑奖状态  1：未发货 2：已发货  3：已收货  有这个字段  -->
							<up-button v-if="state.luckyInfo.cash_address.status===1" type="error" text="等待奖品发放" shape="circle"></up-button>
							<up-button v-else-if="state.luckyInfo.cash_address.status===2" type="error" text="奖品已发放，注意查收" shape="circle"></up-button>
						</block>
					</view>
					<!-- 已参与，未中奖 -->
					<view v-else class="u-p-l-80 u-p-r-80 u-p-t-40">
						<block v-if="state.luckyInfo.draw==='开奖失败'">
							<p class="u-font-25 u-text-center u-p-b-20 u-error-dark">选号总数未达到开奖要求数量</p>
							<up-button type="error" text="开奖失败" disabled plain shape="circle"></up-button>
						</block>
						<block v-else>
							<p class="u-font-25 u-text-center u-p-b-20 u-error-dark">不要灰心，相信幸运总会在下一次光顾你哦！</p>
							<up-button type="warning" text="很遗憾，未中奖" plain shape="circle"></up-button>
						</block>
					</view>
				</block>
				<view v-if="state.user_count>0" class="u-p-t-50">
					<view class="u-font-26 u-text-center u-p-b-10 u-content-color">
						<view>已有{{state.user_count}}人参与，已选{{state.claim||state.luckyInfo.claim}}个幸运号</view>
						<view class="u-flex u-flex-middle u-m-t-20">
							<up-avatar-group :urls="state.urls" size="35" maxCount="15" gap="0.4"></up-avatar-group>
						</view>
					</view>
				</view>
			</block>
		</view>
		<view  class="u-m-l-20 u-m-r-20 u-p-b-40">
			<image mode="widthFix" v-for="(img,index) in state.luckyInfo.images" :key="index" :src="img" style="width: 100%;display: block;"></image>
			
		</view>
		<up-gap height="10" bgColor="#fafafa"></up-gap>
		<view class="u-p-20">
			<p class="u-font-26">* 平台声明</p>
			<p class="u-font-26 u-error-dark u-m-t-20">1、奖品以收到实物为准；</p>
			<p class="u-font-26 u-error-dark u-m-t-10">2、如遇抽奖奖品缺货，平台有权调整为同等价值品质奖品；</p>
			<p class="u-font-26 u-error-dark u-m-t-10">3、奖品签收后，不支持任何理由的换货要求；</p>
			<p class="u-font-26 u-error-dark u-m-t-10 u-p-b-40">4、活动规则最终解释权由“幸运集市”所属公司所有；</p>
		</view>
		<!-- 中奖提示 -->
		<up-popup :show="state.luckyShow" overlayOpacity="0.8" bgColor="transparent" :safe-area-inset-bottom="false" mode="center" :closeable="false" @close="state.luckyShow=false">
			<view class="u-flex u-flex-center">
				<image mode="widthFix" style="width: 320px;height: 569px;" src="@/static/icon/lucky.png"></image>
			</view>
			<view class="u-flex u-flex-center" @click="state.luckyShow=false">
				<up-icon name="close-circle" color="#fff" size="40"></up-icon>
			</view>
		</up-popup>
		<up-keyboard mode="number" :dotDisabled="true" confirmText="确认选号" :show="state.keyboardShow"
			:tips="state.currentNum?state.currentNum:state.currentTxt" customStyle="{color:#000}" @change="valChange"
			@backspace="backspace" @confirm="confirm" @cancel="cancel" @close="keyboardHide"></up-keyboard>
		<up-popup
		:show="state.noCoinShow" 
		overlayOpacity="0.8" 
		bgColor="transparent" 
		:round="10" 
		:safe-area-inset-bottom="false" 
		mode="center" 
		:closeable="false" 
		@close="state.noCoinShow=false">
			<view>
				<view class="u-flex u-flex-middle">
					<image src="@/static/icon/star.png" mode="widthFix" style="width:200rpx;height: 200rpx;"></image>
				</view>
				<p class="u-text-center u-font-30 u-m-t-20 u-text-white">啊哦~ 幸运星不足，邀请好友可+<text class="u-font-44 u-m-l-4 u-m-r-4">50</text>星/人</p>
				<view class="u-m-t-50">
					<up-button type="success" open-type="share" shape="circle" text="邀请好友"></up-button>
				</view>
			</view>
			<view class="u-flex u-flex-center u-m-t-80 u-p-t-40" @click="state.noCoinShow=false">
				<up-icon name="close-circle" color="#fff" size="40"></up-icon>
			</view>
		</up-popup>	
		<up-popup :show="state.ruleShow" :round="10" :safe-area-inset-bottom="false" mode="center" :closeable="true"
			@close="state.ruleShow=false">
			<view class="ruleShowBox">
				<p class="u-text-center u-font-30 u-p-30">抽奖规则</p>
				<view class="u-p-l-40 u-p-r-20 u-p-b-40 u-content-color u-font-28">
					<p class="u-error-dark">一、开奖条件：</p>
					<view class="u-m-t-10 u-content-color">
						<p>1.1 活动到达结束时间并且已选号码大于活动最低要求参与号码数量；</p>
						<p>1.2 如果不符合开奖条件，活动到达开奖时间后会返还活动所消耗的积分；</p>
					</view>
					<p class="u-error-dark u-m-t-20">二、开奖规则：</p>
					<view class="u-m-t-10 u-content-color">
						<p>2.1 活动截止后共放出N个幸运号；</p>
						<p class="u-m-t-10">2.2 N个幸运号累加结果为M；</p>
						<p class="u-m-t-10">2.3 所有幸运号累加之和取最后5位所得结果R为中奖参考值；</p>
						<p class="u-m-t-10">2.4 您的幸运号如果等于R或最接近R，即为中奖号码；</p>
						<p class="u-m-t-10">2.5 如果出现差值相同的两个号码，则取较大的号码作为开奖号码；</p>
					</view>
				</view>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow,
		onShareAppMessage
	} from '@dcloudio/uni-app'
	import {
		onMounted,
		onUnmounted,
		reactive,
		nextTick,
		computed,
		ref,
		defineEmits,
	} from 'vue';
	import {
	  useAuth
	} from '/composables/useAuth';
	import {
		BASE_URL,
		REQUEST_SUCCESS
	} from '/utils/config.js';
	import createApi from '/api/commonAPI.js';
	const commonAPI = createApi(store);
	import {
		useStore
	} from 'vuex';
	const store = useStore();
	const {
		token,
		user_id,
		userInfo,
		hasAuth,
		session_key,
		SET_TOKEN,
		autoLogin,
		setAvatar,
		uploadFile,
		wxLoginByPhone,
		logout,
		login,
		refreshAppId,
		hasSigned,
		account,
		getUserAccount,
	} = useAuth();
	const bgColor = ref('#f15e69');  
	// 定义可以向父组件发送的事件
	const emits = defineEmits(['open-signIn']);
	// 使用 reactive 创建响应式数组  
	const state = reactive({
		pageLength:-1,
		luckyShow: false,
		ruleShow: false,
		isFinish:false,
		luckyInfo:null,
		user_count:0,//已参与人数
		claim:0,//已选出号码总数
		user_nums:[],//当前用户的选号历史
		urls:[],
		noCoinShow:false,
		isFinish:false,
	})
	onLoad(async (options) => {
		state.pageLength=getCurrentPages().length
		if(options.id){
			uni.showLoading({
				title:'加载中...'
			})
			await getLuckyDetail(options.id)
			if(token.value){
				getLuckyUserCount()
				getLuckyCurUserNums()
				getLuckyAvatar()
			}
		}
	});
	// 定义分享内容
	onShareAppMessage(() => {
		return {
			title: '免费参加！' + state.luckyInfo.name,
			path: '/pages/index/index?inviterId='+userInfo.value.id,
			imageUrl: state.luckyInfo.cover,
			success: function (res) {
				uni.showToast({ title: '分享成功' })
				console.log('分享成功', res)
			},
			fail: function (err) {
				uni.showToast({ title: '分享失败', icon: 'none' })
				console.log('分享失败', err)
			}
		}
	})
	function goHome(){
		uni.redirectTo({
			url:'/pages/index/index'
		})
	}
	function goBack(){
		uni.navigateBack()
	}
	async function getLuckyDetail(id) {
		await commonAPI.lucky_detail(id).then(res => {
			if (res.code == REQUEST_SUCCESS) {
				state.luckyInfo = res.data
				const drawTime = new Date(state.luckyInfo.end).getTime(); // 转为毫秒时间戳
				const now = new Date().getTime(); // 当前时间毫秒数
				if (now > drawTime) {
				    state.isFinish=true
				}
				if(state.luckyInfo.draw_user_id===userInfo.value.id){
					uni.vibrateShort();
					state.luckyShow=true
				}
				uni.hideLoading()
			}
		})
	}
	function chooseNum(){
		if(!userInfo.value.nick_name&&!userInfo.value.avatar){
			emits('open-login');
			return false;
		}
		//这里先要判断他的积分是否可以满足单次选号所需
		if(account.value.integral<state.luckyInfo.integral){
			state.noCoinShow=true
			return false;
		}
		state.keyboardShow=true
	}
	const valChange = (val) => {
	  if(state.currentNum.length>4){
	  	uni.showToast({
	  		icon:'none',
	  		title:'只能选择5个数字哦'
	  	})
	  	return false;
	  }
	  state.currentNum += val;
	  // **限制不能以0开头**
	  if (parseInt(state.currentNum)<1) {
		  uni.showToast({
			  icon: 'error',
			  title: '不能以0开头'
		  });
		  state.currentNum=''
	  }
	};
	
	const backspace = () => {
	  // 删除value的最后一个字符
	  if (state.currentNum.length) {
	    state.currentNum = state.currentNum.substr(0, state.currentNum.length - 1);
	  }
	};
	const keyboardHide = () =>{
		state.keyboardShow = false
		state.currentNum=''
	}
	//随机选号
	const randomNum = () =>{
		if(!userInfo.value.nick_name&&!userInfo.value.avatar){
			emits('open-login');
			return false;
		}
		//这里先要判断他的积分是否可以满足单次选号所需
		if(account.value.integral<state.luckyInfo.integral){
			state.noCoinShow=true
			return false;
		}
		state.keyboardShow=true
		let randomNumbers = [];
		// 生成第一个数字，范围在 1-9
		randomNumbers.push(Math.floor(Math.random() * 9) + 1);
		// 生成接下来的4个数字，范围在 0-9
		for (let i = 0; i < 4; i++) {
			randomNumbers.push(Math.floor(Math.random() * 10));
		}
		state.currentNum = randomNumbers.join('');
	}
	//取消选号
	const cancel = () =>{
		state.keyboardShow = false
		uni.showToast({
			icon:'none',
			title:'取消选号'
		})
		state.currentNum=''
	}
	//确认选号
	const confirm = () =>{
		if(state.currentNum.length<5||state.currentNum.length>5){
			uni.showToast({
				icon:'none',
				title:'请选择5个数字哦'
			})
			return false;
		}
		state.keyboardShow = false
		//请求提交选号的接口，判断号码是否可选
		commonAPI.luckyBuy(state.luckyInfo.id,{nums:state.currentNum}).then(res => {
			if (res.code == REQUEST_SUCCESS) {
				if(res.data.has_buy_nums[0]===state.currentNum){
					uni.showToast({
						icon:'error',
						title:'该号码已被选'
					})
					return false;
				}
				if(res.data.can_buy_nums[0]===state.currentNum){
					uni.showToast({
						icon:'success',
						title:'选号成功'
					})
					getLuckyAvatar()
					state.user_count=res.data.user_count
					state.claim=res.data.claim
					state.user_nums=res.data.user_nums
					state.currentNum=''
				}
			}else{
				uni.showToast({
					icon:'none',
					title:res.message
				})
				state.currentNum=''
			}
		})
	}
	//当前活动已参与人数 lucky_user_count
	function getLuckyUserCount(){
		commonAPI.lucky_user_count(state.luckyInfo.id).then(res => {
			if (res.code == REQUEST_SUCCESS) {
				state.user_count = res.data
			}
		})
	}
	//获取当前参与人数
	function getLuckyAllNums(){
		commonAPI.lucky_user_nums(state.luckyInfo.id).then(res => {
			if (res.code == REQUEST_SUCCESS) {
				state.all_join_nums_count = res.data.length
			}
		})
	}
	//获取当前参与人头像 lucky_avatar
	function getLuckyAvatar(){
		state.urls=[]
		commonAPI.lucky_avatar(state.luckyInfo.id).then(res => {
			if (res.code == REQUEST_SUCCESS) {
				res.data.forEach(item=>{
					state.urls.push(item.user_avatar)
				})
			}
		})
	}
	//获取当前参与在当前活动中的选号 lucky_cur_user_nums
	function getLuckyCurUserNums(){
		commonAPI.lucky_cur_user_nums(state.luckyInfo.id).then(res => {
			if (res.code == REQUEST_SUCCESS) {
				state.user_nums = res.data
			}
		})
	}
	const toBuyHistory = () =>{
		uni.navigateTo({
			url:'/pages/userCenter/buyHistory'
		})
	}
	//订阅开始提醒subscribeMessagePreview
	async function subscribeMessagePreview() {
		const templateId = 'WTEdX61eVasY4qO89Xmffs-LeHPiiX8HCsgvMwInzs8'; // 替换为你的模板 ID
		try {
			const res = await uni.requestSubscribeMessage({
				tmplIds: [templateId]
			});
			if (res[templateId] === 'accept') {
				uni.showToast({
					title: '订阅成功'
				});
			} else if (res[templateId] === 'reject') {
				uni.showToast({
					title: '您拒绝了订阅消息，将无法收到通知',
					icon: 'none',
					duration: 1000
				});
			} else if (res[templateId] === 'ban') {
				uni.showToast({
					title: '您已关闭订阅',
					icon: 'none'
				});
			}
		} catch (err) {
			console.error('订阅失败:', err);
			uni.showToast({
				title: '订阅失败，请稍后再试',
				icon: 'none'
			});
		}
	}
	//是否订阅了
	async function subscribeMessage() {
		const templateId = '9DmL-aSZFeLNSuM7egkNoLdRRCqx7sIB2jPcFuY3qU4'; // 替换为你的模板 ID
		try {
			const res = await uni.requestSubscribeMessage({
				tmplIds: [templateId]
			});
			if (res[templateId] === 'accept') {
				uni.showToast({
					title: '订阅成功'
				});
			} else if (res[templateId] === 'reject') {
				uni.showToast({
					title: '您拒绝了订阅消息，将无法收到通知',
					icon: 'none',
					duration: 1000
				});
			} else if (res[templateId] === 'ban') {
				uni.showToast({
					title: '您已关闭订阅',
					icon: 'none'
				});
			}
		} catch (err) {
			console.error('订阅失败:', err);
			uni.showToast({
				title: '订阅失败，请稍后再试',
				icon: 'none'
			});
		}
	}
</script>

<style lang="scss" scoped>
	.u-nav-slot{
		border:1px solid rgba(255,255,255,.2);
		border-radius:30rpx;
		padding:4px 20rpx;
		color:#fff;
		font-size: 26rpx;
		background-color: rgba(255,255,255,.1);
		display: flex;
		align-items: center;
		justify-content: center;
		image{
			width: 34rpx;
			height: 34rpx;
			display: block;
		}
	}
</style>
